package com.dingshi.security;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.dingshi.security.adapter.BreakAdapter;
import com.dingshi.security.adapter.ListAdapter;
import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.DevicesApi;
import com.dingshi.security.api.RepairApi;
import com.dingshi.security.db.SettingLoader;
import com.dingshi.security.entity.DeviceInfo;
import com.dingshi.security.util.StringUtils;
import com.dingshi.security.util.Utils;
import com.dingshi.security.view.DevicePopupWindow;
import com.dingshi.security.view.LoadDialog;

public class RepairCreateActivity extends BaseActivity implements OnClickListener{


	private static final int CAMERA_REQUEST_CODE = 3;
	private static final int RESULT_REQUEST_CODE = 4;
	protected static final int ID_LOADING = 2013;
	private Button btn_take_pic;
	private File currentFile;
	private ArrayList<String> picList;
//	private HorizontalScrollView gallery;
	private LinearLayout mGallery;
	private Button btn_back;
	private TextView title_text;
	private Spinner device_spinner;
	private Spinner break_spinner;
	private ArrayList<DeviceInfo> deviceList = null ,list = null;
	private ArrayList<String> breakList = null;
	private TextView onduty;
	private EditText break_desc;
	private Button btn_reset;
	private boolean break_success = false,device_success = false;
	private Button btn_commit;
	private Button btn_delete;
	private Button btn_rec;
	protected DevicePopupWindow popupWindow;
	private Location location;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.repair_create);
		initTopBar();
		initComponents();
		
		reset();
	}
	
	private void initTopBar() {
		btn_back = (Button)findViewById(R.id.btn_back);
		title_text = (TextView)findViewById(R.id.title_text);
		btn_reset = (Button)findViewById(R.id.btn_refresh);
		btn_reset.setOnClickListener(this);
		btn_reset.setText("重置");
		btn_reset.setVisibility(View.VISIBLE);
		btn_back.setOnClickListener(this);
		title_text.setText("新建报修");
		
	}


	private void initComponents() {
		btn_take_pic = (Button)findViewById(R.id.btn_take_pic);
		btn_take_pic.setOnClickListener(this);
		
//		gallery = (HorizontalScrollView)findViewById(R.id.horizontalScrollView1);
		mGallery = (LinearLayout)findViewById(R.id.gallery);
		btn_rec = (Button)findViewById(R.id.button1);
		btn_rec.setOnClickListener(this);
		
		onduty = (TextView)findViewById(R.id.onduty);
		device_spinner = (Spinner)findViewById(R.id.spinner1);
		break_spinner = (Spinner)findViewById(R.id.spinner2);
		break_desc = (EditText)findViewById(R.id.break_desc);
		
		btn_delete = (Button)findViewById(R.id.btn_delete);
		btn_commit = (Button)findViewById(R.id.btn_commit);
		btn_delete.setOnClickListener(this);
		btn_commit.setOnClickListener(this);
		
		onduty.setText(SettingLoader.getGuardName(this));
		
		break_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if(breakList!=null) {
					break_desc.setText(break_desc.getText().toString()+breakList.get(arg2));	
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});
	}
	
	/**
	 * 重置数据
	 */
	private void reset() {
		if(!break_success) {
			getBreaks("2");
		}
		if(!device_success) {
			getDevices(true);
		}
	}
	
	private void getBreaks(String type) {
		DevicesApi api = new DevicesApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {
			
			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				if (jsonEntity != null) {
					// {"d":[{"__type":"DiaryReturn:r","c":"aaa","t":"01:59:05"}],"t":1}

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							break;
						case 1:// 数组
							JSONArray array = jsonEntity.getJSONArray("d");
							if (array != null) {
								breakList = new ArrayList<String>();
								for (int i = 0; i < array.length(); i++) {
									JSONObject opt = (JSONObject) array.opt(i);
									breakList.add(opt.getString("n"));
								}
								Log.i("Diary", "size is " + breakList.size());
							}
							break_success = true;
							break;
						case -1:// 错误
							dismissDialog(ID_LOADING);
							break;

						default:
							dismissDialog(ID_LOADING);
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					BreakAdapter adapter = new BreakAdapter(RepairCreateActivity.this,breakList);
					break_spinner.setAdapter(adapter);
				}
			}
			
			@Override
			public <T> void onReturnLoading(int requestCode) {
				
			}
			
			@Override
			public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
				
			}
		});
		api.getBreaks(1, this, type);
		
	}
	
	private void getDevices(final boolean getAll) {
		
		DevicesApi api = new DevicesApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {
			
			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				if (jsonEntity != null) {
					// {"d":[{"__type":"DiaryReturn:r","c":"aaa","t":"01:59:05"}],"t":1}
//{"d":[{"__type":"EquipReturn:r","a":"5","c":"SX009","i":"13","la":"40.0507557","ln":"116.2968376","n":"双兴球机41","s":"0","t":"摄像头"}],"t":1}

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							break;
						case 1:// 数组
							JSONArray array = jsonEntity.getJSONArray("d");
							
							if (array != null) {
								list = new ArrayList<DeviceInfo>();
								DeviceInfo info = null;
								for (int i = 0; i < array.length(); i++) {
									info = new DeviceInfo();
									JSONObject opt = (JSONObject) array.opt(i);
									info.setI(opt.getString("i"));
									info.setN(opt.getString("n"));
									info.setC(opt.getString("c"));
									info.setA(opt.getString("a"));
									info.setLa(opt.getString("la"));
									info.setLn(opt.getString("ln"));
									info.setT(opt.getString("t"));
									info.setS(opt.getString("s"));
									list.add(info);
								}
								Log.i("Diary", "size is " + list.size());
								if(!getAll) {
									if(popupWindow!=null) {
										popupWindow.updateUI(location,list);
									}
								}else {
									deviceList = list;
								}
							}
							device_success = true;
							
							break;
						case -1:// 错误
							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					ListAdapter adapter = new ListAdapter(RepairCreateActivity.this,deviceList);
					device_spinner.setAdapter(adapter);
				}
			}
			
			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(ID_LOADING);
			}
			
			@Override
			public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
			}
		});
		if(getAll) {
			api.getDevices(1, this, "1", "0", SettingLoader.getAreaNum(this), null,null);
			
		}else {
			location = SecurityApp.getApp(this).getLocation();
			api.getDevices(1, this, "1", "0", SettingLoader.getAreaNum(this), (location!=null?location.getLatitude()+"":null), (location!=null?location.getLongitude()+"":null));
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ID_LOADING:
			LoadDialog dialog = new LoadDialog(this, "努力加载中。。。");
			return dialog;

		default:
			break;
		}
		return super.onCreateDialog(id);
	}
	
	
	private void saveRepair() {
		String deviceNum = null;
		if(deviceList!=null&&deviceList.size()>0) {
			deviceNum = deviceList.get(device_spinner.getSelectedItemPosition()).getI();
		}
		String breakIn = null;
		if(breakList!=null&&breakList.size()>0) {
			breakIn = breakList.get(break_spinner.getSelectedItemPosition());
		}
		String breakDesc = break_desc.getText().toString();
		/*if(StringUtils.isNullOrEmpty(deviceNum)) {
			Utils.showToast(this, "请选择故障设备");
			return ;
		}
		if(StringUtils.isNullOrEmpty(breakIn)) {
			Utils.showToast(this, "请选择故障描述");
			return ;
		}
		*/
		RepairApi repair = new RepairApi(this);
		repair.setReturnResultListener(new ApiReturnResultListener() {
			
			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
				JSONObject jsonEntity = apiResult.getJsonEntity();
				Log.e("aa", jsonEntity.toString());
				if (jsonEntity != null) {
					// {"d":{"__type":"OperatorReturn:r","r":"3"},"t":0}

					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							JSONObject json = jsonEntity.getJSONObject("d");
							String result = json.getString("r");
							if (!StringUtils.isNullOrEmpty(result)&& 0 < Integer.parseInt(result)) {
								Utils.showToast(RepairCreateActivity.this, "添加成功");
								if(fromOther) {
									Intent intent = new Intent();
									intent.putExtra("diaryNum", result);
									setResult(RESULT_OK, intent);
									finish();
								}else {
									Intent intent = new Intent(RepairCreateActivity.this,HomeActivity.class);
									startActivity(intent);
									finish();
								}
							} else {
								Utils.showToast(RepairCreateActivity.this, "添加失败");
							}
							break;
						case 1:// 数组

							break;
						case -1:// 错误
							Utils.showToast(RepairCreateActivity.this, "添加失败");
							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
			
			@Override
			public <T> void onReturnLoading(int requestCode) {
				showDialog(ID_LOADING);
			}
			
			@Override
			public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
				dismissDialog(ID_LOADING);
			}
		});
		
//		File directory = Environment.getExternalStorageDirectory();
//		
//		File file = new File(directory,"headicon.jpg");
//		ArrayList<String> list = new ArrayList<String>();
//		list.add(file.getAbsolutePath());
		
//		repair.createRepair(1,duty,SettingLoader.getDepartNum(this),"23","fdg",breakDesc,list);//TODO 是编号还是名字
		repair.createRepair(1,SettingLoader.getGuardNum(this),SettingLoader.getDepartNum(this),deviceNum,breakIn,breakDesc,picList);//TODO 是编号还是名字
		
	}
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_take_pic:
			if(picList!=null&&picList.size()>=4) {
				Utils.showToast(this, "只能拍四张照片哦");
				return;
			}
			
			if (Utils.hasSdcard()) {
				File filePath = Utils.getCachePath();
				currentFile = new File(filePath,getFileName());
				Uri outputFileUri = Uri.fromFile(currentFile);
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
			    intent.putExtra("camerasensortype", 2); // 调用前置摄像头
			    intent.putExtra("autofocus", true); // 自动对焦
			    intent.putExtra("fullScreen", false); // 全屏
			    intent.putExtra("outputX", 800);
				intent.putExtra("outputY",600);
			    intent.putExtra("showActionIcons", false);
			 
			    startActivityForResult(intent, RESULT_REQUEST_CODE);
			}else {
				Utils.showToast(RepairCreateActivity.this, getResources().getString(R.string.has_no_sdcard));
			}
			
			break;
		case R.id.btn_back:
			super.onBackPressed();
			break;
		case R.id.btn_commit :
			saveRepair();
			break;
		case R.id.btn_refresh:
			reset();
			break;
		case R.id.btn_delete:
			if(mGallery!=null&&mGallery.getChildCount()>0) {
				mGallery.removeViewAt(mGallery.getChildCount()-1);
				picList.remove(picList.size()-1);
			}
			break;
		case R.id.button1:
			if (popupWindow == null) {
				popupWindow = new DevicePopupWindow(RepairCreateActivity.this);
			}
			popupWindow.setOnItemClickListener(new ItemClickListener() {

				@Override
				public void onItemClickListener(String str) {
					if(deviceList!=null) {
						for(int i=0;i<deviceList.size();i++) {
							if(str.equals(deviceList.get(i).getN())) {
								device_spinner.setSelection(i);
								break;
							}
						}
					}else {
						deviceList = list;
						for(int i=0;i<deviceList.size();i++) {
							if(str.equals(deviceList.get(i).getN())) {
								device_spinner.setSelection(i);
								break;
							}
						}
					}

				}

			});
			popupWindow.show(btn_rec);
			 
			getDevices(false);
			
			break;
		default:
			break;
		}
		
	}


	private String getFileName() {
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
		return "IMG_" + format.format(date) + ".jpg";
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("拍照", "requestCode is " + requestCode + " date is " + data);
		if(RESULT_OK==resultCode) {

			switch (requestCode) {
			case CAMERA_REQUEST_CODE:
				if(Utils.hasSdcard()) {
					if(currentFile!=null) {
						startPhotoZoom(Uri.fromFile(currentFile));
					}
				}else {
					Utils.showToast(RepairCreateActivity.this, getResources().getString(R.string.has_no_sdcard));
				}
				break;
			case RESULT_REQUEST_CODE :
//				if(data!=null) {
//					if(getImageToView(data)) {
//						if(picList==null) {
//							picList = new ArrayList<String>();
//						}
//						if(currentFile!=null) {
//							picList.add(currentFile.getAbsolutePath());
//						}
//
//						updateGallery();
//					}
//				}else {
					if(getImageToView(currentFile)) {
						if(picList==null) {
							picList = new ArrayList<String>();
						}
						if(currentFile!=null) {
							picList.add(currentFile.getAbsolutePath());
						}
						updateGallery();
					}
//				}
				break;
			default:
				break;
			}
		}
	}
	
	private boolean getImageToView(File file) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true; // 当为true时 允许查询图片不为 图片像素分配内存
		Bitmap bmp=BitmapFactory.decodeFile(file.getAbsolutePath(),opts);
		int width = opts.outWidth;
		int hight = opts.outHeight;
		Log.e("", "width is " + width + " hight is " + hight);
		opts.inJustDecodeBounds=false; 
		bmp=BitmapFactory.decodeFile(file.getAbsolutePath(),opts);
		bmp = Bitmap.createScaledBitmap(bmp,  800, 600, false);
//		bmp = Bitmap.createBitmap(bmp, 0, 0, 800, 600);
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(currentFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return bmp.compress(Bitmap.CompressFormat.JPEG, 90, os);
	}

	private void updateGallery() {
		try {
			if(mGallery!=null&&picList!=null) {
				mGallery.removeAllViews();
				LinearLayout.LayoutParams imageLP = new LinearLayout.LayoutParams(Utils.dipToPixels(this, 120),Utils.dipToPixels(this, 120));
				imageLP.setMargins(Utils.dipToPixels(this, 5), 0, Utils.dipToPixels(this, 5), 0);
				imageLP.gravity = Gravity.CENTER_VERTICAL;
				ImageView image = null;
				for(String filepath : picList) {
					image = new ImageView(this);
					try {
						BitmapFactory.Options opt = new BitmapFactory.Options();
						opt.inSampleSize = 4;
						Bitmap decodeFile = BitmapFactory.decodeFile(filepath,opt);
						image.setImageBitmap(decodeFile);
						mGallery.addView(image,imageLP);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
	}

	private boolean getImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			FileOutputStream os = null;
			try {
				os = new FileOutputStream(currentFile);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			return photo.compress(Bitmap.CompressFormat.JPEG, 90, os);
		}
		return false;
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 800);
		intent.putExtra("outputY",600);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, RESULT_REQUEST_CODE);
	}
	
	public interface ItemClickListener {
		public void onItemClickListener(String str);
	}
}